#include "headfile.h"

uint16_t data = 0, s = 0;
extern u8 str[128];
extern bool flag_show;

void UART1_Init(void)
{
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
	
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1);
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1);
	
	GPIO_InitTypeDef GPIO_Struct;
	GPIO_Struct.GPIO_Mode = GPIO_Mode_AF;
	GPIO_Struct.GPIO_OType = GPIO_OType_PP;
	GPIO_Struct.GPIO_Pin = GPIO_Pin_9;
	GPIO_Struct.GPIO_Speed = GPIO_Low_Speed;
	GPIO_Init(GPIOA,&GPIO_Struct);
	
	GPIO_Struct.GPIO_Pin = GPIO_Pin_10;
	GPIO_Struct.GPIO_PuPd = GPIO_PuPd_UP;
	GPIO_Init(GPIOA,&GPIO_Struct);
	
	
	USART_InitTypeDef USART_Struct;
	USART_Struct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
	USART_Struct.USART_BaudRate = 115200;
	USART_Struct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_Struct.USART_Parity = USART_Parity_No;
	USART_Struct.USART_StopBits = USART_StopBits_1;
	USART_Struct.USART_WordLength = USART_WordLength_8b;
	USART_Init(USART1,&USART_Struct);
	
	USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
	USART_Cmd(USART1,ENABLE);
}

void sendData(const u16 * text)
{
	while(*text)
	{
		USART_SendData(USART1,*text);
		while(RESET == USART_GetFlagStatus(USART1,USART_FLAG_TXE));
		text++;
	}
}

void USART1_IRQHandler(void)
{
	if(SET == USART_GetITStatus(USART1,USART_IT_RXNE))
	{
		USART_ClearITPendingBit(USART1,USART_IT_RXNE);
		if(true == flag_show)
		{
			str[s++] = USART_ReceiveData(USART1);
		}
	}
	
}

int fputc(int ch,FILE *p)
{
	USART_SendData(USART1,(uint16_t)ch);
	while(RESET == USART_GetFlagStatus(USART1,USART_FLAG_TXE));
	return ch;
}
